package com.live.proxy.tool;

import android.annotation.SuppressLint;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.widget.Toast;

import androidx.core.content.FileProvider;

import java.io.File;

public class DownloadFileUtil {
    private static BroadcastReceiver FILEreceiver;

    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    public static void downloadFile(Context context, String url, String fileName, boolean isInstall) {
        File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) + "/" + fileName);
        if(file.exists()){
            file.delete();
        }
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        request.setAllowedOverRoaming(false);//漫游网络是否可以下载
        request.setDestinationInExternalFilesDir(context, Environment.DIRECTORY_DOWNLOADS, fileName);
        DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        long mTaskId = downloadManager.enqueue(request);
        //广播接受者，接收下载状态
        FILEreceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                DownloadManager.Query query = new DownloadManager.Query();
                query.setFilterById(mTaskId);//筛选下载任务，传入任务ID，可变参数
                Cursor c = downloadManager.query(query);
                if (c.moveToFirst()) {
                    @SuppressLint("Range")
                    int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
                    switch (status) {
                        case DownloadManager.STATUS_SUCCESSFUL:
                            if (isInstall) {
                                installAPK(context,fileName);
                            }
                            //注销广播
                            context.unregisterReceiver(FILEreceiver);
                            break;
                        case DownloadManager.STATUS_FAILED:
                            Toast.makeText(context, "下载失败", Toast.LENGTH_SHORT).show();
                            //注销广播
                            context.unregisterReceiver(FILEreceiver);
                            break;
                    }
                }
            }
        };
        //注册广播接收者，监听下载状态
        context.registerReceiver(FILEreceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }
    //下载到本地后执行安装
    public static void installAPK(Context context, String fileName) {
        File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) + "/" + fileName);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
        //大于7.0使用此方法24
        Uri apkUri = FileProvider.getUriForFile(context, context.getPackageName()+".Download", file);
        //添加这一句表示对目标应用临时授权该Uri所代表的文件
        intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        context.startActivity(intent);
    }
}